package Server;

import java.sql.SQLException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.codehaus.jettison.json.JSONObject;

import Server.BusinessObjects.User;

@Path("/user")
public class UserRessource {
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("/changePassword/{userId}/{oldPassword}/{newPassword}")
	public String changePassword(@PathParam("userId") int userId,
			@PathParam("oldPassword") String oldPassword,
			@PathParam("newPassword") String newPassword) throws SQLException {

		JSONObject o = new JSONObject();
		User u = User.getUser(userId);

		try {
			if(u.getPassword().equals(oldPassword)) {
				User.changePassword(userId, newPassword);
				o.put("Done", "Passwort wurde geaendert");
			} else {
				o.put("Error", "altes Passwort stimmt nicht");
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return o.toString();
	}
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("/changeUsername/{userId}/{newUsername}")
	public String changeUsername(@PathParam("userId") int userId,
			@PathParam("newUsername") String newUsername) throws SQLException {

		JSONObject o = new JSONObject();
		User u = User.getUser(newUsername);
		try {
			if(u == null) {
				User.changeUsername(userId, newUsername);
				o.put("Done", "Username wurde geaendert");
			} else {
				o.put("Error", "Username exisitiert bereits");
			}
			
						
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return o.toString();
	}
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("/registerUser/{username}/{password}")
	public String registerUser(@PathParam("username") String username,
			@PathParam("password") String password) {

		JSONObject o = new JSONObject();

		try {
			if (username.length() == 0)
				o.put("Error", "Kein Benutzername angegeben");
			else if (password.length() == 0)
				o.put("Error", "Kein Passwort angegeben");
			else {
				User u = User.getUser(username);
				if (u != null)
					o.put("Error", "Benutzer existiert bereits");
				else {
					User.insertPlayer(username, password, false);
					u = User.getUser(username);
					o.put("Done", "neuer User wurde erstellt");
					o.put("UserId", u.getId());
					o.put("UserName", u.getName());
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return o.toString();
	}

}
